package com.wjx.article_sys.controller;

import com.wjx.article_sys.service.impl.AdminServiceImpl;
import com.wjx.article_sys.service.impl.ArticleServiceImpl;
import com.wjx.article_sys.service.impl.CommentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private ArticleServiceImpl articleService;
    @Autowired
    private AdminServiceImpl adminService;
    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private HttpSession session;

    @GetMapping("/tologin")
    public String toLogin(@RequestParam(name = "isLoginBack", defaultValue = "0") int isLoginBack,
                          @RequestParam(name = "isArticleDetailLogin", defaultValue = "0")
                          int isArticleDetailLogin, @RequestParam(name = "aId", defaultValue = "0")
                          Integer aId, Model model) {
        model.addAttribute("isLoginBack", isLoginBack);
        model.addAttribute("isArticleDetailLogin", isArticleDetailLogin);
        model.addAttribute("aId", aId);
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public void login(@RequestParam(name = "isLoginBack", defaultValue = "0") int isLoginBack,
                      @RequestParam(name = "isArticleDetailLogin", defaultValue = "0")
                      int isArticleDetailLogin, @RequestParam(name = "aId", defaultValue = "0") Integer aId,
                      @RequestParam("userName") String userName, @RequestParam("password") String password
                      ) throws Exception {
        adminService.login(userName, password, isLoginBack, isArticleDetailLogin, aId);
    }

    @GetMapping("/logout")
    public String logout() {
        if (session.getAttribute("userName") != null && session.getAttribute("userName") != "空") {
            session.removeAttribute("userName");
            session.removeAttribute("photo");
        }
        return "redirect:/";
    }
}
